package models

import (
	"time"

	"gorm.io/gorm"
)

// FriendRequest 好友申请模型
type FriendRequest struct {
	gorm.Model
	FromUserID int       `json:"from_user_id" gorm:"not null"`
	ToUserID   int       `json:"to_user_id" gorm:"not null"`
	Status     string    `json:"status" gorm:"default:'pending'"` // pending, accepted, rejected
	Message    string    `json:"message"`                         // 申请消息
	CreatedAt  time.Time `json:"created_at"`
}

// CreateFriendRequest 创建好友申请
func CreateFriendRequest(fromUserID, toUserID int, message string) error {
	request := &FriendRequest{
		FromUserID: fromUserID,
		ToUserID:   toUserID,
		Status:     "pending",
		Message:    message,
		CreatedAt:  time.Now(),
	}
	return GetDB().Create(request).Error
}

// GetFriendRequests 获取用户收到的好友申请
func GetFriendRequests(userID int) ([]FriendRequest, error) {
	var requests []FriendRequest
	err := GetDB().Where("to_user_id = ? AND status = ?", userID, "pending").Find(&requests).Error
	return requests, err
}

// GetSentFriendRequests 获取用户发送的好友申请
func GetSentFriendRequests(userID int) ([]FriendRequest, error) {
	var requests []FriendRequest
	err := GetDB().Where("from_user_id = ?", userID).Find(&requests).Error
	return requests, err
}

// UpdateFriendRequestStatus 更新好友申请状态
func UpdateFriendRequestStatus(requestID uint, status string) error {
	return GetDB().Model(&FriendRequest{}).Where("id = ?", requestID).Update("status", status).Error
}

// CheckFriendRequestExists 检查是否已存在好友申请
func CheckFriendRequestExists(fromUserID, toUserID int) bool {
	var request FriendRequest
	return GetDB().Where("from_user_id = ? AND to_user_id = ? AND status = ?",
		fromUserID, toUserID, "pending").First(&request).Error == nil
}

// CheckAlreadyFriends 检查是否已经是好友
func CheckAlreadyFriends(userID1, userID2 int) bool {
	var friend Friend
	return GetDB().Where("(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)",
		userID1, userID2, userID2, userID1).First(&friend).Error == nil
}
